#include <config.h>
#include <fonts_manager.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

static int g_iHzkFd;
static struct stat g_tBuf;
static unsigned char *pucHzkMem;
static unsigned char *pucHzkMemEnd;

static int GbkFontInit(char *pcFileName, unsigned int dwFontSize)
{
	if(16 != dwFontSize)
	{
		DBG_PRINTF("GBK can't support %d fontsize\n", dwFontSize);
		return -1;
	}

	g_iHzkFd = open("HZK16", O_RDONLY);
	if(0 > g_iHzkFd)
	{
		DBG_PRINTF("Can't open HZK16\n");
		return -1;
	}

	if(fstat(g_iHzkFd, &g_tBuf))
	{
		DBG_PRINTF("Can't get hzk stat\n");
		return -1;
	}

	pucHzkMem = (unsigned char *)mmap(NULL, g_tBuf.st_size, PROT_READ, MAP_SHARED, g_iHzkFd, 0);
	if((unsigned char *)-1 == pucHzkMem)
	{
		DBG_PRINTF("Can't mmap hzk\n");
		return -1;
	}

	pucHzkMemEnd = pucHzkMem + g_tBuf.st_size;
	return 0;
}

static int GbkGetFontBitmap(unsigned int dwCode, PT_FontBitmap ptFontBitmap)
{
	int iArea;
	int iWhere;

	int iPenX = ptFontBitmap->iCurOriginX;
	int iPenY = ptFontBitmap->iCurOriginY;

	if(dwCode & 0xffff0000)
	{
		DBG_PRINTF("Hzk can't support this code\n");
		return -1;
	}

	iArea = (dwCode & 0xff) - 0xa1;
	iWhere = ((dwCode >> 8) & 0xff) - 0xa1;

	if ((iArea < 0) || (iWhere < 0))
	{
		DBG_PRINTF("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
		return -1;
	}
	
	ptFontBitmap->iXLeft = iPenX;
	ptFontBitmap->iYTop  = iPenY - 16;
	ptFontBitmap->iXMax  = iPenX + 16;
	ptFontBitmap->iYMax  = iPenY;
	ptFontBitmap->iBpp   = 1;
	ptFontBitmap->iPitch = 2;
	ptFontBitmap->pucBuffer = pucHzkMem + (iArea*94 + iWhere)*32;
	if(ptFontBitmap->pucBuffer >= pucHzkMemEnd)
	{
		return -1;
	}
	ptFontBitmap->iNextOriginX = iPenX + 16;
	ptFontBitmap->iNextOriginY = iPenY;

	return 0;
}

static T_FontOpr g_tGbkFontOpr = {
	.name = "gbk",
	.FontInit = GbkFontInit,
	.GetFontBitmap = GbkGetFontBitmap,
};

int GbkRegister(void)
{
	return RegisterFontOpr(&g_tGbkFontOpr);
}

